﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Controller;
using BusinessModel;
using ManageStore.Config;
using ManageStore.Common;
using Controller.DataProvider;
using ManageStore.IViews;
using BaseUtilities;
using System.Diagnostics;

namespace ManageStore.Forms
{
    public partial class FrmBuy : BaseForm, IBuyProductView
    {
        public FrmBuy()
        {
            InitializeComponent();

            dgvBuyOrderDetail.AutoGenerateColumns = false;
            BuyProductCtr = new BuyProductCtr(this);
            BindData();

            EvtNew += BuyProductCtr.MtdNew;
            EvtEdit += BuyProductCtr.MtdEdit;
            EvtDelete += BuyProductCtr.MtdDelete;
            EvtSave += BuyProductCtr.MtdSave;
            EvtGetAllChilds += BuyProductCtr.MtdGetAllChilds;
            EvtAdd += BuyProductCtr.MtdAdd;
            EvtRemove += BuyProductCtr.MtdRemove;
            EvtLoadProduct += BuyProductCtr.MtdLoadProduct;
            EvtLoadSupplier += BuyProductCtr.MtdLoadSupplier;
        }
        private void FrmProduct_Load(object sender, EventArgs e)
        {
            dgvBuyOrderDetail.AutoGenerateColumns = false;
            CreateTreeview();
            cbbName.SelectedIndex = -1;
        }

        #region Properties =============================================
        private BuyProductCtr _BuyProductCtr;
        public BuyProductCtr BuyProductCtr
        {
            get { return _BuyProductCtr; }
            set { _BuyProductCtr = value; }
        }

        public bool IsLoaded { get; set; }
        #endregion Properties ==========================================End

        #region Private Methods ==========================================
        //----------------------------------------
        private void BindData()
        {
            buyProductCtrBindingSource.DataSource = BuyProductCtr;

            //bdsProduct.DataSource = BuyProductCtr.LstProduct;
            cbbCode.DataSource = cbbName.DataSource = BuyProductCtr.LstProduct;

            //bdsUnit.DataSource = BuyProductCtr.LstUnit;
            cbbUnit.DataSource = BuyProductCtr.LstUnit;
            //bdsUnit1.DataSource = BuyProductCtr.LstUnit;
            cbbUnit1.DataSource = BuyProductCtr.LstUnit;
            //bdsUnit2.DataSource = BuyProductCtr.LstUnit;
            cbbUnit2.DataSource = BuyProductCtr.LstUnit;
            //bdsUnit3.DataSource = BuyProductCtr.LstUnit;
            cbbUnit3.DataSource = BuyProductCtr.LstUnit;
            //bdsUnitWholeSale.DataSource = BuyProductCtr.LstUnit;
            cbbUnitWholeSale.DataSource = BuyProductCtr.LstUnit;

            bdsUnitLevel1.DataSource = BuyProductCtr.UnitChangeLevel1;
            bdsUnitLevel2.DataSource = BuyProductCtr.UnitChangeLevel2;
            bdsUnitLevel3.DataSource = BuyProductCtr.UnitChangeLevel3;
            bdsUnitLevelWholeSale.DataSource = BuyProductCtr.UnitChangeWholeSale;

            //bdsDiscount.DataSource = BuyProductCtr.LstDiscountType;
            cbbDiscountType.DataSource = BuyProductCtr.LstDiscountType;
            //bdsSupplier.DataSource = BuyProductCtr.LstSupplier;
            cbbSupplier.DataSource = BuyProductCtr.LstSupplier;
            dgvBuyOrderDetail.DataSource = BuyProductCtr.LstBuyOrderDetail;
            //bdsListDetail.DataSource = BuyProductCtr.LstBuyOrderDetail;
        }
        //----------------------------------------
        private void CreateTreeview()
        {
            TreeNode oTreeNode = new TreeNode();
            oTreeNode.Name = "0";
            oTreeNode.Text = "Gốc";
            trvParentType.Nodes.Clear();
            trvParentType.Nodes.Add(oTreeNode);
            OnEvtGetAllChilds((result) =>
            {
                IList<ProductType> lstPro = result as IList<ProductType>;
                CreateSubNode(oTreeNode, lstPro);
                trvParentType.SelectedNode = oTreeNode;
                oTreeNode.Expand();
            });
        }
        //----------------------------------------
        private void CreateSubNode(TreeNode pTreeNode, IList<ProductType> pLstProductType)
        {
            pLstProductType.ToList().ForEach((item) =>
            {
                TreeNode _TreeNode = new TreeNode();
                _TreeNode.Name = item.Id.ToString();
                _TreeNode.Text = item.Name;
                pTreeNode.Nodes.Add(_TreeNode);
                OnEvtGetAllChilds((childs) =>
                {
                    IList<ProductType> lstPro = childs as IList<ProductType>;
                    CreateSubNode(_TreeNode, lstPro);
                }, item.Id);
                //IList<ProductType> lstPro = _ProductTypeCtr.GetAllChilds(item.Id).ToResult<IList<ProductType>>();
            });
        }
        #endregion Private Methods ==========================================End

        #region View Handler ==========================================
        //----------------------------------------
        public void ReloadData()
        {
            IsLoaded = false;
            dgvBuyOrderDetail.DataSource = null;
            dgvBuyOrderDetail.DataSource = BuyProductCtr.LstBuyOrderDetail; ;
        }
        //----------------------------------------
        public event ActionInvoke EvtGetAllChilds;
        public void OnEvtGetAllChilds(Action<object> pAction, params object[] pParams)
        {
            if (EvtGetAllChilds != null)
                EvtGetAllChilds(pAction, pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtAdd;
        public void OnEvtAdd(params object[] pParams)
        {
            if (EvtAdd != null)
                EvtAdd(pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtRemove;
        public void OnEvtRemove(params object[] pParams)
        {
            if (EvtRemove != null)
                EvtRemove(pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtLoadProduct;
        public void OnEvtLoadProduct(params object[] pParams)
        {
            if (EvtLoadProduct != null)
                EvtLoadProduct(pParams);
        }
        //----------------------------------------
        public event MethodInvoke EvtLoadSupplier;
        public void OnEvtLoadSupplier(params object[] pParams)
        {
            if (EvtLoadSupplier != null)
                EvtLoadSupplier(pParams);
        }

        //----------------------------------------
        public override bool BeforeHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtNew":
                    errorProvider1.Clear();
                    break;
                case "EvtRemove":
                    if (pParams.Contains("NoItem"))
                    {
                        MessageBox.Show("Chưa có hàng nào được chọn.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return true;
                    }
                    result = MessageBox.Show("Bạn có chắc muốn bỏ hàng này không?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK;
                    break;
                case "EvtDelete":
                    result = MessageBox.Show("Bạn có chắc muốn xóa phiếu nhập này không?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK;
                    break;
                case "EvtSave":
                    break;
            }
            return result;
        }
        //----------------------------------------
        public override bool ErrorHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtAdd":
                    string sError = "Không thể thêm vào được.";
                    if (pParams.Count() == 1)
                    {
                        Dictionary<string, string> lstError = pParams[0] as Dictionary<string, string>;
                        if (lstError != null && lstError.Count > 0)
                        {
                            sError = "Dữ liệu nhập vào không hợp lệ.";
                        }
                        else
                        {
                            sError = pParams[0].ToString();
                        }
                    }
                    MessageBox.Show(sError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
            return result;
        }
        //----------------------------------------
        public override bool CompletedHandler(string pEventName, params object[] pParams)
        {
            bool result = true;
            switch (pEventName)
            {
                case "EvtNew":
                    dgvBuyOrderDetail.ClearSelection();
                    cbbCode.Focus();
                    break;
                case "EvtEdit":
                    cbbCode.Focus();
                    errorProvider1.Clear();
                    break;
                case "EvtAdd":
                case "EvtRemove":
                case "EvtDelete":
                case "EvtSave":
                    OnEvtNew();
                    break;
                case "EvtLoadProduct":
                    cbbCode.DataSource = cbbName.DataSource = BuyProductCtr.LstProduct;
                    if (cbbName.SelectedValue != null)
                        cbbCode.SelectedValue = cbbName.SelectedValue;
                    break;
                case "EvtLoadSupplier":
                    cbbSupplier.DataSource = BuyProductCtr.LstSupplier;
                    break;
            }
            return result;
        }
        //----------------------------------------
        public override bool ValidationHandler(string pColumnName, params object[] pParams)
        {
            bool result = true;
            if (!string.IsNullOrWhiteSpace(pColumnName))
            {
                // Get Error control.
                Control ctl = null;
                switch (pColumnName)
                {
                    case "ProductName":
                    case "ProductId":
                        ctl = cbbName;
                        break;
                    case "Quantity":
                        ctl = txtQuanlity;
                        break;
                    case "BuyPriceUnit":
                        ctl = txtBuyPriceUnit;
                        break;
                    case "SalePriceUnit":
                        ctl = txtSalePriceUnit;
                        break;
                }
                // Set Control Error.
                if (ctl != null)
                {
                    if (pParams.Count() == 1 && !string.IsNullOrEmpty(pParams[0].ToString()))
                        errorProvider1.SetError(ctl, pParams[0].ToString());
                    else
                        errorProvider1.SetError(ctl, null);
                }

            }
            return result;
        }
        #endregion View Handler ==========================================End

        #region Dotnet Methods ==========================================
        //----------------------------------------
        private void btnNew_Click(object sender, EventArgs e)
        {
            //NewProduct();
            OnEvtNew();
        }
        //----------------------------------------
        private void btnAdd_Click(object sender, EventArgs e)
        {
            OnEvtAdd();
        }
        //----------------------------------------
        private void btnRemove_Click(object sender, EventArgs e)
        {
            OnEvtRemove();
        }
        //----------------------------------------
        private void btnSave_Click(object sender, EventArgs e)
        {
            OnEvtSave();
        }
        //----------------------------------------
        private void btnDelete_Click(object sender, EventArgs e)
        {
            OnEvtDelete();
        }
        //----------------------------------------
        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //----------------------------------------
        private void dgvBuyOrderDetail_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dgvBuyOrderDetail.ClearSelection();
            IsLoaded = true;
        }
        //----------------------------------------
        private void dgvBuyOrderDetail_SelectionChanged(object sender, EventArgs e)
        {
            if (IsLoaded && dgvBuyOrderDetail.SelectedRows.Count > 0)
            {
                OnEvtEdit(dgvBuyOrderDetail.SelectedRows[0].DataBoundItem);
            }
        }
        //----------------------------------------
        private void cbbProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!IsLoaded)
            {
                return;
            }
            //int? iProductId = _BuyProductCtr.BuyOrderDetail.ProductId;
            int? iTypeId = null;
            ComboBox cbb = sender as ComboBox;
            TreeNode oTreeNode = null;
            if (cbb.SelectedValue != null)
            {
                oTreeNode = trvParentType.Nodes.Find(cbb.SelectedValue.ToString(), true).FirstOrDefault();
                trvParentType.CollapseAll();
                oTreeNode.Parent.Expand();
                trvParentType.SelectedNode = oTreeNode;

                iTypeId = int.Parse(cbb.SelectedValue.ToString());
            }
            else
            {
                trvParentType.SelectedNode = oTreeNode;
            }
            //CbbProductLoad(iTypeId);
            OnEvtLoadProduct(iTypeId);
        }
        //----------------------------------------
        private void trvParentType_AfterSelect(object sender, TreeViewEventArgs e)
        {
                txtTypeSelected.Text = e.Node.Text;
                //_ProductCtr.Product.TypeId = int.Parse(e.Node.Name);
                if (e.Node.Nodes.Count == 0)
                {
                    lblTypeId.Text = e.Node.Name;
                }
        }
        //----------------------------------------
        //----------------------------------------
        private void FrmProduct_Activated(object sender, EventArgs e)
        {
            if (!IsLoaded)
            {
                IsLoaded = true; 
            }
        }
        //----------------------------------------
        private void cbbName_Validated(object sender, EventArgs e)
        {
            if (!this.Disposing && cbbName.SelectedValue == null && !string.IsNullOrWhiteSpace(cbbName.Text))
            {
                _BuyProductCtr.BuyOrderDetail.ProductId = default(int);
                int iProductId = default(int);
                if (MessageBox.Show("Chưa có hàng hóa này./r/nBạn muốn tạo mới không?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    //OnEvtNew();
                    FrmProduct oFrmProduct = new FrmProduct();
                    oFrmProduct.EvtSaved += (sen, ea) =>
                    {
                        int.TryParse(sen.ToString(), out iProductId);
                    };
                    oFrmProduct.Activated += (senl, eal) =>
                    {
                        oFrmProduct.ProductCode = cbbCode.Text;
                        oFrmProduct.ProductName = cbbName.Text;
                    };
                    oFrmProduct.IsDialog = true;
                    oFrmProduct.ShowDialog();
                }
                if (iProductId != default(int))
                {
                    OnEvtLoadProduct();
                    cbbName.SelectedValue = iProductId;
                    txtQuanlity.SelectAll();
                    txtQuanlity.Focus();
                }
                else //if (cbbCode.SelectedValue != null)
                {
                    cbbCode.SelectedValue = default(int);
                    errorProvider1.SetError(cbbName, "Hàng hòa này không tồn tại");
                }
            }
        }
        //----------------------------------------
        private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txtNumber = sender as TextBox;
            if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
            }
            else
                errorProvider1.SetError(sender as Control, null);
        }
        //----------------------------------------
        private void txtNumber_Validating(object sender, CancelEventArgs e)
        {
            TextBox txtNumber = sender as TextBox;
            txtNumber.Text = txtNumber.Text.Trim();
            if (!CommonUtils.IsNumber(txtNumber.Text.Replace(",","").Replace(".","")))
            {
                txtNumber.Text = "0";
                e.Cancel = true;
            }
        }
        #endregion Dotnet Methods ==========================================End

        private void txt_Enter(object sender, EventArgs e)
        {
            TextBox txt = sender as TextBox;
            txt.SelectAll();
        }

        private void cbbSupplier_Validated(object sender, EventArgs e)
        {
            if (!this.Disposing && cbbSupplier.SelectedValue == null && !string.IsNullOrWhiteSpace(cbbSupplier.Text))
            {
                _BuyProductCtr.BuyOrderDetail.SupplierId = default(int);
                int iSupplierId = default(int);
                if (MessageBox.Show("Chưa có nhà cung cấp này./r/nBạn muốn tạo mới không?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    FrmSupplier oFrmSupplier = new FrmSupplier();
                    oFrmSupplier.EvtSaved += (sen, ea) =>
                    {
                        int.TryParse(sen.ToString(), out iSupplierId);
                    };
                    oFrmSupplier.Activated += (senl, eal) =>
                    {
                        oFrmSupplier.SupplierName = cbbSupplier.Text;
                    };
                    oFrmSupplier.IsDialog = true;
                    oFrmSupplier.ShowDialog();
                }
                if (iSupplierId != default(int))
                {
                    OnEvtLoadSupplier();
                    txtQuanlity.SelectAll();
                    txtQuanlity.Focus();
                }
                else
                {
                    cbbSupplier.Text = string.Empty;
                }
                cbbSupplier.SelectedValue = iSupplierId;
            }
        }
    }
}
